package com.baymax.utils;

import cn.hutool.core.collection.CollUtil;
import com.baymax.common.Constant;
import com.baymax.datascope.enums.DataScopeEnum;
import com.baymax.entity.vo.SysRoleVO;
import com.baymax.exception.GlobalException;
import com.baymax.security.entity.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户认证信息工具类
 *
 * @Author: baymax
 * @CreateTime: 2023/3/30 16:28
 * @Version: 1.0
 */
public class SecurityUtil {

    /**
     * 获取当前认证用户
     */
    public static SecurityUser getCurrentUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (SecurityUser) authentication.getPrincipal();
    }

    /**
     * 获取当前用户
     */
    public static SecurityUser getUser() {
        try {
            return getCurrentUserInfo();
        } catch (Exception e) {
            throw new GlobalException("用户未授权");
        }
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        try {
            return getCurrentUserInfo().getUserId();
        } catch (Exception e) {
            throw new GlobalException("用户未授权");
        }
    }

    /**
     * 获取用户名
     */
    public static String getUsername() {
        try {
            return getCurrentUserInfo().getUsername();
        } catch (Exception e) {
            throw new GlobalException("用户未授权");
        }
    }

    /**
     * 获取当前用户最高的数据权限枚举
     */
    public static DataScopeEnum getDataScopeEnum() {
        List<SysRoleVO> roleVOList = getCurrentUserInfo().getRoleVOList();
        if (CollUtil.isEmpty(roleVOList)) {
            return null;
        }
        List<Integer> dataScopeList = roleVOList.stream().map(SysRoleVO::getDataScope).sorted().collect(Collectors.toList());
        return DataScopeEnum.findByDataScope(dataScopeList.get(Constant.ZERO));
    }

    /**
     * 是否为管理员
     */
    public static Boolean isAdmin() {
        List<SysRoleVO> roleVOList = getCurrentUserInfo().getRoleVOList();
        if (CollUtil.isEmpty(roleVOList)) {
            return false;
        }
        return roleVOList.stream().map(SysRoleVO::getRoleTag).collect(Collectors.toSet()).contains(Constant.ADMIN_TAG);
    }

}
